package com.sdry.web.controller.agreement;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sdry.base.BaseController;
import com.sdry.entity.agreement.Agreement;
import com.sdry.entity.agreement.AgreementExample;
import com.sdry.entity.agreement.AgreementExample.Criteria;
import com.sdry.entity.base.Staff;
import com.sdry.service.agreement.AgreementServise;
import com.sdry.service.approval.ApprovalService;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;


/**
 * @ClassName: AgreementController
 * @Description: 合同协议
 * @author tdd
 * @date 2018年8月29日
 * @version V1.0
 */
@Controller
@RequestMapping("/agreement")
public class AgreementController extends BaseController{

    @Resource
    private AgreementServise agreementServise;
    @Resource
    private ApprovalService approvalService;


    /**
     * 去合同协议列表页面
     * @return
     */
    @RequestMapping("/pageToAgreement")
    public String pageToAgreement(Model model ,String aremark9) {
    	if(StringUtil.isNotEmpty(aremark9)){
    		model.addAttribute("aremark9",aremark9);
    	}
        return "/agreement/agreement";
    }

    /**
     * 去合同协议详情页面
     * @return
     */
    @RequestMapping("/pageToAgreementXq")
    public String pageToAgreementXq(Model model,Long id) {
        if (null != id && id != 0){
            Agreement agreement = agreementServise.selectByPrimaryKey(id);
            model.addAttribute("agreement",agreement);
        }
        return "/agreement/agreementXq";
    }

    /**
     * 添加合同协议
     * @param response 响应
     * @param agreement 合同协议实体
     * @throws Exception 异常
     */
    @RequestMapping("/insertAgreement")
    public void insertAgreement(HttpServletRequest request, HttpServletResponse response, Agreement agreement) throws Exception {

        int affact = 0;

        //当前时间
        SimpleDateFormat sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String   date   =   sDateFormat.format(new Date());

        AgreementExample example = new AgreementExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(agreement.getAname() != null && agreement.getAname() != "") {
            createCriteria.andAnameEqualTo(agreement.getAname());
        }
        List<Agreement> agreements = agreementServise.selectByExample(example);
        if(agreements.size() == 0){
			//判断session
            HttpSession session  = request.getSession();
            //从session中取出用户身份信息
            Staff staffSession = (Staff) session.getAttribute("staff");
            if(staffSession != null){
            	agreement.setAremark4(staffSession.getSname());
            	agreement.setAremark9(String.valueOf(staffSession.getStaid()));
            }
        	agreement.setCreatedate(date);
        	agreement.setAremark6("0");
            //添加
            affact = agreementServise.insertSelective(agreement);
        }
        ResponseUtil.write(response, affact);
    }

    /**
     * 带条件的分页查询合同协议信息
     * @param request 请求
     * @param response 响应
     * @param rows 每页记录数
     * @param page 页数
     * @param agreement 合同协议信息实体
     * @throws Exception 异常
     */
    @RequestMapping("/selectAgreementList")
    public void selectAgreementList(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "page",required = false)int page,
                                   @RequestParam(value = "rows",required = false)int rows,
                                    Agreement agreement) throws Exception {

    	PageHelper.startPage(page, rows);

        AgreementExample example = new AgreementExample();
        example.setOrderByClause("Aremark6 asc, createDate desc");
        Criteria createCriteria =  example.createCriteria();
    	//名称模糊
        if(agreement.getAname() != null && agreement.getAname() != "") {
    		createCriteria.andAnameLike("%"+agreement.getAname()+"%");
    	}
    	//客户模糊
        if(agreement.getClient() != null && agreement.getClient() != "") {
            createCriteria.andClientEqualTo(agreement.getClient());
        }
        //审批id查询
        if(agreement.getAremark() != null && agreement.getAremark() != "") {
        	createCriteria.andAremarkEqualTo(agreement.getAremark());
        }
        //创建人id查询
        if(agreement.getAremark9() != null && agreement.getAremark9() != "") {
        	createCriteria.andAremark9EqualTo(agreement.getAremark9());
        }
        List<Agreement> list = agreementServise.selectByExample(example);
		
		PageInfo<Agreement> info = new PageInfo<Agreement>(list);
    	
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total", info.getTotal());
        jsonObject.put("rows", info.getList());
        ResponseUtil.write(response, jsonObject);
    }

    /**
     * 根据条件查询合同协议信息
     * @param response 响应
     * @param agreement 条件
     * @throws Exception 异常
     */
    @RequestMapping("/selectAgreementByExample")
    public void selectAgreementByExample(HttpServletResponse response, Agreement agreement) throws Exception {
        AgreementExample example = new AgreementExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(agreement.getAname() != null && agreement.getAname() != "") {
            createCriteria.andAnameEqualTo(agreement.getAname());
        }
        //客户
        if(agreement.getClient() != null && agreement.getClient() != "") {
            createCriteria.andClientEqualTo(agreement.getClient());
        }
        //审批id查询
        if(agreement.getAremark() != null && agreement.getAremark() != "") {
        	createCriteria.andAremarkEqualTo(agreement.getAremark());
        }
        List<Agreement> agreements = agreementServise.selectByExample(example);
        //将对象转化为json
        //JSONObject json = JSONObject.fromObject(agreements);
        JSONArray json = JSONArray.fromObject(agreements);
        ResponseUtil.write(response, json);
    }
    /**
     * 根据id查询合同协议信息
     * @param response 响应
     * @param id 合同协议id
     * @throws Exception 异常
     */
    @RequestMapping("/selectAgreementById")
    public void selectAgreementById(HttpServletResponse response, Long id) throws Exception {

        Agreement agreement = agreementServise.selectByPrimaryKey(id);
        //将对象转化为json
        JSONObject json = JSONObject.fromObject(agreement);
        ResponseUtil.write(response, json);
    }

    /**
     * 修改合同协议信息
     * @param response 响应
     * @param agreement 合同协议信息
     * @throws Exception 异常
     */
    @RequestMapping("/editAgreement")
    public void editAgreement( HttpServletResponse response,
                               Agreement agreement) throws Exception {

        int affct = 0;

        AgreementExample example = new AgreementExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(agreement.getAname() != null && agreement.getAname() != "") {
            createCriteria.andAnameEqualTo(agreement.getAname());
        }
        List<Agreement> agreements = agreementServise.selectByExample(example);
        if(agreements.size() == 0){
            //修改
            affct = agreementServise.updateByPrimaryKeySelective(agreement);
        }else if(agreements.size() == 1 && agreements.get(0).getAid().equals(agreement.getAid())){
            affct = agreementServise.updateByPrimaryKeySelective(agreement);
        }
        ResponseUtil.write(response, affct);
    }
    /**
     * 归档合同协议信息
     * @param response 响应
     * @param agreement 合同协议信息
     * @throws Exception 异常
     */
    @RequestMapping("/filedAgreement")
    public void filedAgreement(HttpServletRequest request, HttpServletResponse response,
    		Agreement agreement) throws Exception {
    	
    	int affct = 0;
    	agreement.setAremark6("1");
    	//当前时间
        SimpleDateFormat sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String   date   =   sDateFormat.format(new Date());
        agreement.setAremark8(date);
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff staffSession = (Staff) session.getAttribute("staff");
        if(staffSession != null){
        	agreement.setAremark7(staffSession.getSname());
        }
    	affct = agreementServise.updateByPrimaryKeySelective(agreement);
    	ResponseUtil.write(response, affct);
    }

    /**
     * 批量删除
     * @param response 响应
     * @param ids 合同协议id
     * @throws Exception 异常
     */
    @RequestMapping("/deleteAgreement")
    public void deleteAgreement( HttpServletResponse response, String ids) throws Exception {

        int affact = agreementServise.deleteByPrimaryKeys(ids);
        ResponseUtil.write(response, affact);
    }
    
    /**
     * @throws Exception 
     * 
     */
    @RequestMapping("/editAremark")
    public void editAremark( HttpServletResponse response,Agreement agreement) throws Exception {
    	
    	int affct = 0;
    	
    	if(agreement.getAremark1() != null && "" != agreement.getAremark1()) {
    		String[] split = agreement.getAremark1().split(",");
        	for (String s : split) {
    			Long aid = Long.valueOf(s);
    			agreement.setAid(aid);
    			Agreement agreement2 = agreementServise.selectByPrimaryKey(aid);
    			String aremark = agreement2.getAremark();
    			String aremark2 = agreement.getAremark();
    			agreement.setAremark2(aremark+","+aremark2);
    			affct = agreementServise.updateByPrimaryKeySelective(agreement);
    		}
    	}
    	
    	if(affct == 0 && agreement.getAremark() != null && agreement.getAremark() !="") {
    		Long approvalId = Long.valueOf(agreement.getAremark());
    		approvalService.deleteByid(approvalId);
    	}
    	ResponseUtil.write(response, affct);
    }

    /**
     * 修改合同协议信息
     * @param response 响应
     * @param agreement 合同协议信息
     * @throws Exception 异常
     */
    @RequestMapping("/editHtml")
    public void editHtml( HttpServletResponse response,
                               Agreement agreement) throws Exception {
        int affct = 0;
        affct = agreementServise.updateByPrimaryKeySelective(agreement);
        ResponseUtil.write(response, affct);
    }
}
